package com.metaio.Example;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import com.metaio.sdk.jni.LLACoordinate;

public class SendData {
	public LLACoordinate location;
	public String category, jsonString;
	public String distance;
	public JSONObject jsonSend, jsonReceive;

	public SendData(LLACoordinate loc, String cat, String dist){
		this.location=loc;
		this.category=cat;
		this.distance=dist;
		jsonSend = new JSONObject();
	}

	public JSONObject sendRequest() {

		try {			
			jsonSend.put("X", location.getLongitude());
			jsonSend.put("Y", location.getLatitude());
			jsonSend.put("Category", category);
			jsonSend.put("Distance", distance);
			HttpParams httpParams = new BasicHttpParams();
			HttpClient httpclient = new DefaultHttpClient(httpParams);
			String URL = "http://192.168.0.11/Project/makepoints.php?" +
					"X="+location.getLongitude()+"&Y="+location.getLatitude()+
					"&Category="+category+"&Distance="+distance;
			HttpPost request = new HttpPost(URL);
			//request.setEntity(new ByteArrayEntity(jsonSend.toString().getBytes("UTF8")));
			//request.setHeader("json", jsonSend.toString());
			HttpResponse response = httpclient.execute(request);
			HttpEntity rslts = response.getEntity();
			InputStream is = rslts.getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
				System.out.println("Line: "+line);
			}
			is.close();
			jsonString = sb.toString();
			try {
				jsonReceive = new JSONObject(jsonString);
			} catch (JSONException e) {
				Log.e("JSON Parser", "Error parsing data " + e.toString());
			}			
			return jsonReceive;
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	} 
}